package com.fz.song.web.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fz.song.framework.common.R;
import com.fz.song.web.entity.User;
import com.fz.song.web.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 77088
 * @title: OptimisticLockingController
 * @projectName idempotent-demo
 * @description: TODO
 * @date 2021/11/119:13
 */

@Api(tags = "幂等性demo-乐观锁")
@Slf4j
@RestController
@RequestMapping("idempotent")
public class OptimisticLockingController {

    @Autowired
    private IUserService userService;


    @ApiOperation(value = "修改用户信息", notes = "使用乐观锁修改用户信息")
    @GetMapping("saveUserInfoByVersion")
    public R saveUserInfoByVersion(Integer id, String name) {
        User user = userService.getById(id);
        LambdaUpdateWrapper<User> wapper = new LambdaUpdateWrapper<>();
        wapper.set(User::getName, name);
        wapper.setSql("version =version +1");
        wapper.eq(User::getId, id);
        wapper.eq(User::getVersion, user.getVersion());
        boolean update = userService.update(wapper);
        if (!update) {
            saveUserInfoByVersion(id, name);
        }
        return R.ok("修改用户信息成功");
    }

    @ApiOperation(value = "乐观转账", notes = "乐观转账")
    @GetMapping("transfer")
    public R transfer() {
        //用户id为1的给用户id为2的转账100;
        Boolean bool = userService.transferOptimistic(1, 2, 100);
        return R.ok("转账", bool);
    }


}
